﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Linq;

namespace Legend.Web.QueryString
{
    /// <summary>
    /// Manages serialization of a dictionary to a query string.
    /// </summary>
    public class QueryStringSerializer : 
        IQueryStringSerializer
    {
        /// <summary>
        /// Serializes the specified dictionary to a query string.
        /// </summary>
        /// <param name="keyValuePairs">The key value pairs to write to the query string.</param>
        /// <returns>A query string.</returns>
        public string Serialize(IDictionary<string,string> keyValuePairs)
        {
            var result = new StringBuilder();

            foreach (var pair in keyValuePairs)
            {
                if (result.Length > 1)
                {
                    result.Append("&");
                }

                result.Append(HttpUtility.UrlEncode(pair.Key));
                result.Append("=");
                result.Append(HttpUtility.UrlEncode(pair.Value));
            }

            return result.ToString();
        }

        /// <summary>
        /// Gets a dictionary of key value pairs that's contained
        /// in the specified query string.
        /// </summary>
        /// <param name="queryString">The query string to get values from.</param>
        /// <returns>The parsed query.</returns>
        public IDictionary<string, string> Parse(string queryString)
        {
            if (string.IsNullOrEmpty(queryString))
            {
                return new Dictionary<string, string>();
            }

            return
                (from pair in queryString.Split('&')
                let splitPair = pair.Split('=')
                select splitPair)
                .ToDictionary(k => HttpUtility.UrlDecode(k[0]), v => HttpUtility.UrlDecode(v[1]));
        }
    }
}
